package summary;

import java.util.ArrayList;
import java.util.List;
import java.util.Stack;

/**
 * @Author: 海琳琦
 * @Date: 2022/3/13 15:13
 * https://leetcode-cn.com/problems/find-mode-in-binary-search-tree/
 */
public class Title501 {

    static class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;

        public TreeNode() {
        }

        public TreeNode(int val) {
            this.val = val;
        }

        public TreeNode(int val, TreeNode left, TreeNode right) {
            this.val = val;
            this.left = left;
            this.right = right;
        }
    }


    public int[] findMode(TreeNode root) {
        List<Integer> result = new ArrayList<>();
        Stack<TreeNode> stack = new Stack<>();
        TreeNode pre = null;
        int count = 0;
        int max = 0;
        while (root != null || !stack.isEmpty()) {
            while (root != null) {
                stack.push(root);
                root = root.left;
            }
            root = stack.pop();
            if (pre == null || pre.val != root.val) {
                count = 1;
            } else {
                count++;
            }
            if (count > max) {
                result.clear();
                max = count;
                result.add(root.val);
            } else if (count == max) {
                result.add(root.val);
            }
            pre = root;
            root = root.right;
        }
        return result.stream().mapToInt(Integer::intValue).toArray();
    }

    int max, count;
    TreeNode pre;

    public int[] findMode3(TreeNode root) {
        max = 0;
        count = 0;
        pre = null;
        List<Integer> result = new ArrayList<>();
        dfs(result, root);
        int[] arr = new int[result.size()];
        int index = 0;
        for (Integer temp : result) {
            arr[index++] = temp;
        }
        return arr;
    }

    private void dfs(List<Integer> result, TreeNode root) {
        if (root == null) {
            return;
        }
        dfs(result, root.left);
        if (pre == null || root.val != pre.val) {
            count = 1;
        } else {
            count++;
        }
        if (count > max) {
            result.clear();
            result.add(root.val);
            max = count;
        } else if (count == max) {
            result.add(root.val);
        }
        pre = root;
        dfs(result, root.right);
    }

    public static void main(String[] args) {

    }
}
